<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <link rel="stylesheet" href="./source/css/reset-1.3.3.css">
  <link rel="stylesheet" href="./source/css/demo.css">
</head>

<body>
  <div class="plugin-wrap">
    <div class="length-info">已添加<span class="picture-num">0</span>张图片</div>
    <div><progress id="progressBar" value="0" max="100" style="width:100%;"></progress></div>
    <div class="imgWrap clearfix">
      <div class="addBtn">
        <input id="upload" type="file" multiple="multiple">
      </div>
    </div>
    <div class="submit">上传</div>
  </div>
</body>
<script>
  var uploadBtn = document.querySelector('#upload')
  var addBtn = document.querySelector('.addBtn')
  var wrap = document.querySelector('.imgWrap')
  var submit = document.querySelector('.submit')
  var progress = document.querySelector('#progressBar')
  uploadBtn.addEventListener('change', upfile, false)

  var formData = new FormData()

  function upfile() {

    var files = this.files
    var filelength = files.length

    if (filelength) {

      for (var i = 0; i < filelength; i++) {
        var file = files[i]

        // fileReader对象读取文件内容
        var reader = new FileReader()

        // FileReader读取的内容可以是file文件或者blob格式数据
        reader.readAsDataURL(file)
        // readDataURL返回URL格式的字符串
        reader.onload = function (result) {

          var preview = document.createElement('div')
          wrap.insertBefore(preview, addBtn)
          preview.classList.add('preview')
          var img = document.createElement('img')
          preview.appendChild(img)
          var del = document.createElement('span')
          del.classList.add('delete')
          preview.appendChild(del)
          var result = result.target.result
          
          img.src = result
          img.name = file.name

          // 获取压缩后的blob
          var blob = canvasDataURL(result)
          formData.append(file.name,blob)
         
          // 判断当前图片数量，达到最大上传数量则隐藏上传按钮
          var previewsImg = document.getElementsByClassName('preview')
          var pictureNum = previewsImg.length

          document.querySelector('.picture-num').textContent = pictureNum

          if (pictureNum >= 6) {

            addBtn.style.display = 'none'
          }

          // 删除图片
          del.addEventListener('click', function (e) {
            // 将当前图片从formData删除  
            var deleteFile = e.target.previousSibling.name

            formData.delete(deleteFile)
            console.log(formData)

            for (var key of formData.keys()) {
              console.log(key)
            }
            e.target.parentElement.parentElement.removeChild(e.target.parentElement)

            // 图片数少于6张，则显示上传按钮
            var imgs = document.getElementsByClassName('preview').length
            document.querySelector('.picture-num').textContent = imgs

            if (imgs < 6) {
              addBtn.style.display = 'block'
            }
          })
        }
      }
    }
  }


  // canvas重绘图片，获得压缩后的图片数据
  function canvasDataURL(path) {
    
    var img = new Image();
    img.src = path;
    img.onload = function () {
      
      var that = this;
      // 默认按比例压缩
      var w = that.width,
          h = that.height,
          scale = w / h;
      var quality = 0.6; // 默认图片质量为0.6
      //生成canvas
      var canvas = document.createElement('canvas');
      var ctx = canvas.getContext('2d');
      // 创建属性节点
      var anw = document.createAttribute("width");
      anw.nodeValue = w;
      var anh = document.createAttribute("height");
      anh.nodeValue = h;
      canvas.setAttributeNode(anw);
      canvas.setAttributeNode(anh);
      ctx.drawImage(that, 0, 0, w,h);
      // wrap.appendChild(canvas)   
      
      // quality值越小，所绘制出的图像越模糊
      // 回调函数返回base64的值
      var base64 = canvas.toDataURL('image/jpeg', quality);
      
      // 将base64格式的urldata数据转化为blob文件
      var blob = convertBase64UrlToBlob(base64)

      return blob
    }
  }


  //  将以base64的图片url数据转换为Blob
  function convertBase64UrlToBlob(urlData){
    var arr = urlData.split(','), mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--){
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {type:mime});
  }



  function sendData() {

    var xhr;

    if(window.XMLHttpRequest){
      xhr = new XMLHttpRequest();
    }else{
      xhr = new ActiveXObject('Microsoft.XMLHTTP');
    }

    xhr.upload.onprogress = function(e) {

      e = e || event;
      if (e.lengthComputable) {
        // progressBar.max = e.total;
        progressBar.value = Math.floor(e.loaded/e.total * 100);
        
      }
    }

    xhr.onload = function() {
      if( xhr.status === 200 ) {
        alert('上传成功')
      }else {
        alert('上传失败')
      }
    }

    xhr.open('post','./demo.json',true);
    // xhr.setRequestHeader("content-type",data.type);
    xhr.send(formData);
  }


  submit.addEventListener('click',sendData)

</script>

</html>